from sqlalchemy import text,or_,and_
from flask import Blueprint,request
from model.model import Advertise,House,Order,Comment,house_facility,Facility
from tools.tools import my_router,item2dict,ord_limit
from flask_login import login_user,login_required,logout_user,current_user
from db_init import db
import time
from catch import local_cache

house = Blueprint('house',__name__)

# 获取房屋
@house.route('/ad',methods=['get'])
# @local_cache.cached(timeout=10)
def ad():
    start_t = time.time()
    ads = Advertise.query.filter_by().all()
    print(time.time() - start_t)
    return my_router(200, item2dict(ads))

# 获取一个房屋的信息
@house.route('/<int:house_id>',methods=['get'])
def house_info(house_id):
    house = House.query.get(house_id)
    ret_house = item2dict(house)
    ret_house['facility'] = item2dict(house_facility)
    return  my_router(200,item2dict(House.query.get(house_id)))

@house.route('/<int:house_id>',methods=['get'])
def house_info_icon(h_id):
    return my_router(200,item2dict(Facility.query.all()))

#修改房屋的信息
@house.route('/update/<int:house_id>',methods=['put'])
def update_house_info(house_id):
    house_data = request.json
    House.query.filter_by(id=house_id).update(house_data)
    db.session.commit()
    return my_router(200)

# 删除房屋信息
@house.route('/delete/<int:house_id>',methods=['delete'])
def delete_house_info(house_id):
    House.query.filter_by(id=house_id).delete()
    db.session.commit()
    return my_router(200)
# from werkzeug.datastructures import ImmutableMultiDict
#
# # 报错的时候最好用，报错的话看源码
# class MyDict(ImmutableMultiDict):
#     def haha(self):
#         print('我真帅')

#获取房子的订单并排序
@house.route('/',methods=['get'])
def get_house():
    # args = MyDict(request.args)
    # args.haha()
    # data = args
    # bouse = House.query.filter_by(live=0,**data).all()
    # return  my_router(200,item2dict(bouse))
    data = dict(request.args)
    order = data.pop('order')
    # 瀑布流
    # 限制每页的数量
    limit = data.pop('limit')
    # 按照最后一位的商品id来进行排序
    end_id = int(data.pop('end_id'))
    # 订单的时间字段
    start_t = int(data.pop('start_time'))
    end_t = int(data.pop('end_time'))
    # 筛选出来所有的不空闲的订单
    orders = Order.query.filter(start_t <= Order.end_time <= end_t).all()
    # House.query.filter(House.live == 0, House.id.__gt__(end_id)筛选出来所有的符合日期的订单
    # filter(*[getattr(House, k) == v for k, v in data.items() 筛选出来所在地区的房屋信息，k就是城区，v是对应的数据，以字典的形式存储
    sql = House.query.filter(House.live == 0, House.id.__gt__(end_id)) \
        .filter(*[getattr(House, k) == v for k, v in data.items()])
    for ord in orders:
        # 如果房屋的id和所要的订单的房屋id不冲突，就说明房子可以供租客入住
        sql = sql.filter(House.id != ord.house_id)
    # 瀑布流分页
    house = sql.order_by(text(order)).limit(limit).all()
    return my_router(200,item2dict(house))

# 评论
@house.route('/comment/<int:h_id>',methods=['get'])
def get_house_comment(h_id):
    c_id= request.args.get('c_id')
    # 先从评论表中筛选出当前的房屋的评论
    sql = Comment.query.filter(Comment.house_id == h_id)
    # 如果存在
    if c_id:
        # 他的评论筛选出来
        sql = sql.filter(Comment.root_id == c_id)
    else:
        # 当前根评论返回没有
        sql = sql.filter(Comment.beau == None)
    # 将刷选出来的数据转成列表
    comments = item2dict(sql.all())
    # 先筛选出来评论
    # comments = Comment.query.filter(Comment.house_id == h_id).all()
    # 遍历循环
    tem_templat = {v['id'] : v for v in comments}
    # 定义空的字典
    ret_data = []
    # 循环遍历
    for _,v in tem_templat.items():
        beau = tem_templat.get(v['beau'],None)
        if not beau:
            # 将主评论添加进字典中
            ret_data.append(v)
        #不在的话
        else:
            # 获取主评论
            # beau = tem_templat.get(v['beau'])
            # 获取主评论下的子评论，将两个列表拼接，数据量不大可以直接+
            # 如果数据量大可以用append,append性能快 +号快，好理解
            beau['son'] = beau.get('son',[]) + [v]
    # 返回结果，输出
    return my_router(200,ret_data)

# 更新评论然后如果是跟评论的话，数量+1
@house.route('/comment/<int:h_id>',methods=['post'])
def post_house_comment(h_id):
    data = request.json
    # 评论数 + 1
    if 'root_id' in data:
        Comment.query.filter_by(id=data['root_id']).update({'num':Comment.num + 1})
    # 加新评论
    db.session.add(Comment(**data))
    db.session.commit()
    return my_router(200)

# 删除评论
@house.route('/del/<int:h_id>',methods=['delete'])
def del_house_comment(h_id):
    Comment.query.filter_by(id=h_id).delete()
    db.session.commit()
    return my_router(200)

@house.route('/add_house_by_user',methods=['post'])
@login_required
def add_house_by_user():
    print(current_user)
    # 判断是不是房东
    data = request.json
    data['master_id'] = current_user.id
    if current_user.landlord:
        houses = House(**data)
        db.session.add(houses)
        db.session.commit()
        # print(houses.id)
        return my_router(200,item2dict(houses))
    return my_router(413)


